package ink.sunflower.security.confg;

import ink.sunflower.security.filter.TokenAuthenticationFilter;
import ink.sunflower.security.filter.TokenLoginFilter;
import ink.sunflower.security.security.DefaultPasswordEncoder;
import ink.sunflower.security.security.TokenLogoutHandler;
import ink.sunflower.security.security.TokenManager;
import ink.sunflower.security.security.UnauthorizedEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author zhaokuii11@163.com
 * @create 2022-06-05 23:25
 * @Description
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)//使用表达式时间方法级别的安全性 4个注解可用
public class TokenWebSecurityConfig extends WebSecurityConfigurerAdapter {
    //自定义查询数据库用户名密码和权限信息
    private UserDetailsService userDetailsService;
    // token管理工具类（生成token）
    private TokenManager tokenManager;
    // 密码管理工具类
    private DefaultPasswordEncoder defaultPasswordEncoder;
    // redis操作工具类
    private RedisTemplate redisTemplate;

    @Autowired
    public TokenWebSecurityConfig(
            TokenManager tokenManager,
            RedisTemplate redisTemplate,
            DefaultPasswordEncoder defaultPasswordEncoder,
            UserDetailsService userDetailsService

    ) {
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
        this.defaultPasswordEncoder = defaultPasswordEncoder;
        this.userDetailsService = userDetailsService;
    }

    /**
     * 配置设置
     * 设置退出的地址和token，redis操作地址
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().
                authenticationEntryPoint(new UnauthorizedEntryPoint()) //没有权限访问的时候访问我们自己写的类
                .and().csrf().disable() //csrf关闭
                .authorizeRequests()   //请求
                .anyRequest().authenticated() //权限
                .and().logout().logoutUrl("/admin/acl/index/logout")//退出的路径
                .addLogoutHandler(new TokenLogoutHandler(tokenManager, redisTemplate)) //退出的逻辑
                .and()
                .addFilter(new TokenLoginFilter(authenticationManager(), tokenManager, redisTemplate)) //认证过滤器
                .addFilter(new TokenAuthenticationFilter(authenticationManager(), tokenManager, redisTemplate))//授权过滤器
                .httpBasic();
    }

    /**
     * 调用userDetailsService和密码处理
     */
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(defaultPasswordEncoder);
    }

    /**
     * 配置哪些请求不拦截，可以直接访问
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring() //忽略
                .antMatchers("/api/**", "/swagger-ui.html/**");
    }
}
